<?php

namespace App\Http\Controllers\Api\V1;

use App\Models\User;
use App\Jobs\CloseGoldRecordJob;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Cache;
use App\Http\Controllers\Api\V1\Resources\GoldWasteResource;
use App\Services\ApplyGoldWastesSubsidy\ApplyGoldWastesOrder;
use App\Services\ApplyGoldWastesSubsidy\ApplyGoldWastesSubsidy;
use App\Http\Controllers\Api\V1\Requests\ApplyGoldWastesOrderRequest;
use App\Http\Controllers\Api\V1\Requests\ApplyGoldWastesSubsidyRequest;

class GoldWastesController extends Controller
{
	public function index(): JsonResponse
	{
		/**
		 * @var User $user
		 */
		$user = request()->user();
        $wastes = $user->goldWastes()->orderByDesc('id')->paginate();
		return response()->json([
            'money' => $user->myAllGoldWastesMoney(),
            'records' => GoldWasteResource::collection($wastes),
        ]);
	}

    public function subsidy()
    {
        $lock = Cache::lock('apply_subsidies', 15);

        try {

            if (! $lock->get()) fail('处理中...请勿频繁操作');

            $request = app(ApplyGoldWastesSubsidyRequest::class);

            /**
             * @var User $user
             */
            $user = $request->user();

            need_paycode($user);

            app(ApplyGoldWastesSubsidy::class, ['user' => $user])->apply();

            $user->resetPayCodeTry();

            return response(null, 204);

        } finally {
            $lock->release();
        }
    }

    public function order()
    {
        $lock = Cache::lock('take_waste_products', 15);

        try {

            if (! $lock->get()) fail('处理中...请勿频繁操作');

            $request = app(ApplyGoldWastesOrderRequest::class);

            /**
             * @var User $user
             */
            $user = $request->user();
            $address = $request->getAddress();

            need_paycode($user);

            app(ApplyGoldWastesOrder::class, [
                'user' => $user,
                'address' => $address,
            ])->apply();

            $user->resetPayCodeTry();

            return response(null, 204);

        } finally {
            $lock->release();
        }
    }
}
